package com.lkl.demo.provider.config;

import com.lkl.demo.common.constant.RabbitMQConstant;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MyConfirmListener implements RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //init方法会在创建当前MyConfirmListener对象之后执行
    @PostConstruct //加上该注解的方法，会在实例化对象之后执行
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        //参数b表示消息确认结果  参数s表示发送的消息
        if (b) {
            System.out.println("消息成功发送到交换机！");
        } else {
            System.out.println("消息发送到交换机失败！");
            //消息发送失败，重发消息
            rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_NAME, RabbitMQConstant.ROUTER_KEY_EXCHANGE, s);
        }
    }
}
